package com.education.expenses.assembler;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * User: alpoloz
 * Date: 7/11/12
 * Time: 6:46 PM
 */
//can't be inherited more than once because in this case method GetClassOfGenericType won't return correct class.
public abstract class GenericAssembler<E, DTO> {

    private Class getClassOfGenericType(int index) {
        ParameterizedType parameterizedType =
                (ParameterizedType) getClass().getGenericSuperclass();
        return (Class) parameterizedType.getActualTypeArguments()[index];
    }

    @SuppressWarnings("unchecked")
    private Class<DTO> getDTOClass() {
        return (Class<DTO>) getClassOfGenericType(1);
    }

    @SuppressWarnings("unchecked")
    private Class<E> getEntityClass() {
        return (Class<E>) getClassOfGenericType(0);
    }

    public DTO toDTO(E entity) {
        try {
            DTO dto = getDTOClass().newInstance();
            BeanUtils.copyProperties(dto, entity);
            return dto;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public E fromDTO(DTO dto) {
        try {
            E entity = getEntityClass().newInstance();
            BeanUtils.copyProperties(entity, dto);
            return entity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<DTO> toDTOs(Collection<E> entities) {
        ArrayList<DTO> dtos = new ArrayList<DTO>();
        for (E entity : entities) {
            dtos.add(toDTO(entity));
        }
        return dtos;
    }

    public List<E> fromDTOs(Collection<DTO> dtos) {
        ArrayList<E> entities = new ArrayList<E>();
        for (DTO dto : dtos) {
            entities.add(fromDTO(dto));
        }
        return entities;
    }
}
